package com.zjcloud.jwgl.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zjcloud.common.utils.DateUtils;
import com.zjcloud.common.utils.SecurityUtils;
import com.zjcloud.jwgl.mapper.AcScheduleAlgorithmConfigMapper;
import com.zjcloud.jwgl.domain.AcScheduleAlgorithmConfig;
import com.zjcloud.jwgl.service.IAcScheduleAlgorithmConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * 排课算法配置Service业务层处理
 * 
 * @author zjcloud
 * @date 2024-12-19
 */
@Service
public class AcScheduleAlgorithmConfigServiceImpl implements IAcScheduleAlgorithmConfigService 
{
    private static final Logger log = LoggerFactory.getLogger(AcScheduleAlgorithmConfigServiceImpl.class);

    @Autowired
    private AcScheduleAlgorithmConfigMapper acScheduleAlgorithmConfigMapper;

    /**
     * 查询排课算法配置
     * 
     * @param id 排课算法配置主键
     * @return 排课算法配置
     */
    @Override
    public AcScheduleAlgorithmConfig selectAcScheduleAlgorithmConfigById(Long id)
    {
        return acScheduleAlgorithmConfigMapper.selectAcScheduleAlgorithmConfigById(id);
    }

    /**
     * 查询排课算法配置列表
     * 
     * @param acScheduleAlgorithmConfig 排课算法配置
     * @return 排课算法配置
     */
    @Override
    public List<AcScheduleAlgorithmConfig> selectAcScheduleAlgorithmConfigList(AcScheduleAlgorithmConfig acScheduleAlgorithmConfig)
    {
        return acScheduleAlgorithmConfigMapper.selectAcScheduleAlgorithmConfigList(acScheduleAlgorithmConfig);
    }

    /**
     * 新增排课算法配置
     * 
     * @param acScheduleAlgorithmConfig 排课算法配置
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAcScheduleAlgorithmConfig(AcScheduleAlgorithmConfig acScheduleAlgorithmConfig)
    {
        // 设置默认值
        if (acScheduleAlgorithmConfig.getEliteRatio() == null) {
            acScheduleAlgorithmConfig.setEliteRatio(0.05);
        }
        acScheduleAlgorithmConfig.setCreateTime(DateUtils.getNowDate());
        acScheduleAlgorithmConfig.setCreateBy(SecurityUtils.getUsername());
        return acScheduleAlgorithmConfigMapper.insertAcScheduleAlgorithmConfig(acScheduleAlgorithmConfig);
    }

    /**
     * 修改排课算法配置
     * 
     * @param acScheduleAlgorithmConfig 排课算法配置
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAcScheduleAlgorithmConfig(AcScheduleAlgorithmConfig acScheduleAlgorithmConfig)
    {
        // 如果要设置为默认配置，先清除其他默认配置
        if (acScheduleAlgorithmConfig.getIsDefault() != null && "1".equals(acScheduleAlgorithmConfig.getIsDefault())) {
            acScheduleAlgorithmConfigMapper.clearDefaultConfig();
        }
        
        acScheduleAlgorithmConfig.setUpdateTime(DateUtils.getNowDate());
        acScheduleAlgorithmConfig.setUpdateBy(SecurityUtils.getUsername());
        return acScheduleAlgorithmConfigMapper.updateAcScheduleAlgorithmConfig(acScheduleAlgorithmConfig);
    }

    /**
     * 批量删除排课算法配置
     * 
     * @param ids 需要删除的排课算法配置主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAcScheduleAlgorithmConfigByIds(Long[] ids)
    {
        return acScheduleAlgorithmConfigMapper.deleteAcScheduleAlgorithmConfigByIds(ids);
    }

    /**
     * 删除排课算法配置信息
     * 
     * @param id 排课算法配置主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteAcScheduleAlgorithmConfigById(Long id)
    {
        return acScheduleAlgorithmConfigMapper.deleteAcScheduleAlgorithmConfigById(id);
    }

    /**
     * 查询默认算法配置
     * 
     * @return 默认配置
     */
    @Override
    public AcScheduleAlgorithmConfig selectDefaultConfig()
    {
        return acScheduleAlgorithmConfigMapper.selectDefaultConfig();
    }

    /**
     * 根据算法类型查询配置列表
     * 
     * @param algorithmType 算法类型
     * @return 配置列表
     */
    @Override
    public List<AcScheduleAlgorithmConfig> selectConfigsByAlgorithmType(String algorithmType)
    {
        return acScheduleAlgorithmConfigMapper.selectConfigsByAlgorithmType(algorithmType);
    }

    /**
     * 根据配置名称查询配置
     * 
     * @param configName 配置名称
     * @return 配置信息
     */
    @Override
    public AcScheduleAlgorithmConfig selectConfigByName(String configName)
    {
        return acScheduleAlgorithmConfigMapper.selectConfigByName(configName);
    }

    /**
     * 设置默认配置
     * 
     * @param id 配置ID
     * @param isDefault 是否设为默认
     * @return 结果
     */
    @Override
    @Transactional
    public boolean setDefaultConfig(Long id, Boolean isDefault)
    {
        try {
            if (isDefault != null && isDefault) {
                // 先清除所有默认配置标记
                acScheduleAlgorithmConfigMapper.clearDefaultConfig();
                // 设置新的默认配置
                int result = acScheduleAlgorithmConfigMapper.setDefaultConfig(id);
                return result > 0;
            } else {
                // 取消默认配置
                int result = acScheduleAlgorithmConfigMapper.cancelDefaultConfig(id);
                return result > 0;
            }
        } catch (Exception e) {
            log.error("设置默认配置失败", e);
            return false;
        }
    }
    
    /**
     * 设置默认配置（兼容性方法）
     * 
     * @param id 配置ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean setDefaultConfig(Long id)
    {
        return setDefaultConfig(id, true);
    }

    /**
     * 查询启用的配置列表
     * 
     * @return 配置列表
     */
    @Override
    public List<AcScheduleAlgorithmConfig> selectEnabledConfigs() {
        return acScheduleAlgorithmConfigMapper.selectEnabledConfigList();
    }

    /**
     * 验证配置参数
     * 
     * @param config 配置信息
     * @return 验证结果
     */
    @Override
    public Map<String, Object> validateConfig(AcScheduleAlgorithmConfig config)
    {
        Map<String, Object> result = new HashMap<>();
        boolean isValid = true;
        StringBuilder errorMsg = new StringBuilder();
        
        // 验证配置名称
        if (!StringUtils.hasText(config.getConfigName())) {
            isValid = false;
            errorMsg.append("配置名称不能为空; ");
        }
        
        // 验证算法类型
        if (!StringUtils.hasText(config.getAlgorithmType())) {
            isValid = false;
            errorMsg.append("算法类型不能为空; ");
        }
        
        // 验证优先级
        if (config.getPriority() != null && (config.getPriority() < 1 || config.getPriority() > 100)) {
            isValid = false;
            errorMsg.append("优先级必须在1-100之间; ");
        }
        
        result.put("isValid", isValid);
        result.put("errorMsg", errorMsg.toString());
        return result;
    }

    /**
     * 复制配置
     * 
     * @param id 源配置ID
     * @param newConfigName 新配置名称
     * @return 新配置ID
     */
    @Override
    @Transactional
    public Long copyConfig(Long id, String newConfigName)
    {
        try {
            // 获取源配置
            AcScheduleAlgorithmConfig sourceConfig = acScheduleAlgorithmConfigMapper.selectAcScheduleAlgorithmConfigById(id);
            if (sourceConfig == null) {
                throw new RuntimeException("源配置不存在");
            }
            
            // 创建新配置
            AcScheduleAlgorithmConfig newConfig = new AcScheduleAlgorithmConfig();
            newConfig.setConfigName(newConfigName.trim());
            newConfig.setAlgorithmType(sourceConfig.getAlgorithmType());
            newConfig.setPopulationSize(sourceConfig.getPopulationSize());
            newConfig.setMaxGenerations(sourceConfig.getMaxGenerations());
            newConfig.setCrossoverRate(sourceConfig.getCrossoverRate());
            newConfig.setMutationRate(sourceConfig.getMutationRate());
            newConfig.setEliteRate(sourceConfig.getEliteRate());
            newConfig.setEliteRatio(sourceConfig.getEliteRatio() != null ? sourceConfig.getEliteRatio() : 0.05);
            newConfig.setConvergenceThreshold(sourceConfig.getConvergenceThreshold());
            newConfig.setIsDefault(0); // 复制的配置不设为默认
            newConfig.setStatus("1"); // 启用状态
            newConfig.setAlgorithmTypeId(sourceConfig.getAlgorithmTypeId());
            newConfig.setTemplateId(sourceConfig.getTemplateId());
            newConfig.setOptimizationStrategy(sourceConfig.getOptimizationStrategy());
            newConfig.setVersion("1.0");
            newConfig.setUsageCount(0);
            newConfig.setSuccessCount(0);
            newConfig.setAverageScore(0.0);
            newConfig.setRemark("复制自: " + sourceConfig.getConfigName());
            
            // 插入新配置
            int result = acScheduleAlgorithmConfigMapper.insertAcScheduleAlgorithmConfig(newConfig);
            if (result > 0) {
                return newConfig.getConfigId();
            } else {
                throw new RuntimeException("复制配置失败");
            }
        } catch (Exception e) {
            log.error("复制配置失败", e);
            throw new RuntimeException("复制配置失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取推荐配置
     * 
     * @param algorithmType 算法类型
     * @param courseCount 课程数量
     * @param classroomCount 教室数量
     * @return 推荐配置
     */
    @Override
    public AcScheduleAlgorithmConfig getRecommendedConfig(String algorithmType, Integer courseCount, Integer classroomCount)
    {
        // 根据课程数量和教室数量推荐合适的配置
        List<AcScheduleAlgorithmConfig> configs = acScheduleAlgorithmConfigMapper.selectConfigsByAlgorithmType(algorithmType);
        
        if (configs.isEmpty()) {
            return null;
        }
        
        // 简单的推荐逻辑：优先返回默认配置，如果没有默认配置则返回第一个启用的配置
        for (AcScheduleAlgorithmConfig config : configs) {
            if ("1".equals(config.getIsDefault())) {
                return config;
            }
        }
        
        for (AcScheduleAlgorithmConfig config : configs) {
            if ("1".equals(config.getStatus())) {
                return config;
            }
        }
        
        return configs.get(0);
    }
}